package com.administrator.cloudapplication.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.administrator.cloudapplication.Interface.NearItemClick;
import com.administrator.cloudapplication.R;
import com.administrator.cloudapplication.activitys.NearDetailActivity;
import com.administrator.cloudapplication.adapter.NearLibraryAdapter;
import com.administrator.cloudapplication.base.BaseFragment;
import com.administrator.cloudapplication.callback.ReqCallBack;
import com.administrator.cloudapplication.constant.Urls;
import com.administrator.cloudapplication.models.NearLibraryModel;
import com.administrator.cloudapplication.tools.GsonUtils;
import com.administrator.cloudapplication.tools.HttpUtils;
import com.administrator.cloudapplication.tools.LocationUtils;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 程序的第三个页面，显示附近的场馆。
 */
public class NearFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2, ReqCallBack, AdapterView.OnItemClickListener, NearItemClick {
    View mView;
    Spinner mSpinner, nSpinner;
    PullToRefreshListView mPullToRefreshListView;
    ArrayList<NearLibraryModel.DataBean> mDataBean = new ArrayList<>();
    NearLibraryAdapter mNearLibraryAdapter;
    String type = "";
    String mile = "";
    int page = 1;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    private boolean isFirstLoc = true;
    String[] spdata = {};
    String[] nspdata = {};
    String longitude;
    String dimension;
    private boolean ifIsDown = true;
    private boolean first1 = true;
    private boolean first2 = true;
    private ArrayList<NearLibraryModel.DataBean> tempData = new ArrayList<>();


    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_near, container, false);
        spdata = getActivity().getResources().getStringArray(R.array.library);
        nspdata = getActivity().getResources().getStringArray(R.array.distance);
        mSpinner = (Spinner) mView.findViewById(R.id.sp_near_library);
        nSpinner = (Spinner) mView.findViewById(R.id.sp_near_distance);
        mPullToRefreshListView = (PullToRefreshListView) mView.findViewById(R.id.refresh_near);
        mPullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullToRefreshListView.setOnItemClickListener(this);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, spdata);
        ArrayAdapter<String> nArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, nspdata);
        arrayAdapter.setDropDownViewResource(R.layout.spinner_near_text);
        nArrayAdapter.setDropDownViewResource(R.layout.spinner_near_text);
        mSpinner.setAdapter(arrayAdapter);
        nSpinner.setAdapter(nArrayAdapter);
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                if (first2) {
                    first2 = false;
                    return;
                }
                switch (position) {
                    case 0:
                        type = "";
                        requestWeb();
                        break;
                    case 1:
                        type = "library";
                        requestWeb();
                        break;
                    case 2:
                        type = "CVenueInfo";
                        requestWeb();
                        break;
                    case 3:
                        type = "repository";
                        requestWeb();
                        break;
                    case 4:
                        type = "other";
                        requestWeb();
                        break;
                }
                mDataBean.clear();
                page = 1;
                requestWeb();
            }

            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        nSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                if (first1) {
                    first1 = false;
                    return;
                }
                switch (position) {

                    case 0:
                        mile = "";
                        requestWeb();
                        break;
                    case 1:
                        mile = "1";
                        requestWeb();
                        break;
                    case 2:
                        mile = "2";
                        requestWeb();
                        break;
                    case 3:
                        mile = "5";
                        requestWeb();
                        break;
                    case 4:
                        mile = "10";
                        requestWeb();
                        break;
                }
                mDataBean.clear();
                page = 1;
                requestWeb();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        mPullToRefreshListView.setOnRefreshListener(this);
        mNearLibraryAdapter = new NearLibraryAdapter(getActivity(), mDataBean, this);
        mPullToRefreshListView.setAdapter(mNearLibraryAdapter);
        return mView;
    }

    @Override
    protected void initData() {
        //开启地图定位功能，获取当前位置的坐标
        mLocationClient = new AMapLocationClient(getActivity().getApplicationContext());
        mLocationOption = LocationUtils.getDefaultOption();
        mLocationClient.setLocationListener(locationListener);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    private void requestWeb() {
        showLoading();
        String url = Urls.LIBRARY_LIST;
        HashMap<String, String> param = new HashMap();
        param.put("curpage", page + "");
        param.put("cate", type);
        param.put("mile", mile);
        param.put("xcor", dimension);
        param.put("ycor", longitude);
        HttpUtils.getInstance(getActivity()).requestPostByAsyn(url, param, this, 0);
    }

    @Override
    protected void initPrepare() {

    }

    @Override
    protected void onInvisible() {

    }


    @Override
    public void onReqSuccess(String result, int flag) {
        stopLoading();
        if (mPullToRefreshListView.isRefreshing()) {
            mPullToRefreshListView.onRefreshComplete();
        }
        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONArray array = jsonObject.getJSONArray("data");
            Object object = array.get(0);
            if (null == object || "null".equals(object.toString())) {
                Toast.makeText(getActivity(), "没有更多了", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NearLibraryModel mNearLibraryModel = GsonUtils.json2Bean(result, NearLibraryModel.class);
        tempData.clear();
        tempData.addAll(mNearLibraryModel.getData());
        if (tempData.size() > 0) {
            page++;
            if (ifIsDown) {
                mDataBean.clear();
                page = 1;
            }
        }
        mDataBean.addAll(mNearLibraryModel.getData());
        mNearLibraryAdapter.notifyDataSetChanged();
    }

    @Override
    public void onReqFailed(String errorMsg, int flag) {
        Toast.makeText(getActivity(), "请检查您的网络", Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        ifIsDown = true;
        page = 1;
        requestWeb();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        ifIsDown = false;
        page++;
        requestWeb();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

    }


    @Override
    public void onClick(NearLibraryModel.DataBean mDataBean) {
        Intent intent = new Intent(getActivity(), NearDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("mDataBean", mDataBean);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    if (isFirstLoc) {
                        isFirstLoc = false;
                        longitude = String.valueOf(aMapLocation.getLatitude());
                        dimension = String.valueOf(aMapLocation.getLongitude());
                        Toast.makeText(getActivity().getApplicationContext(), "定位成功,当前坐标为:经度"
                                + longitude + "/纬度" + dimension, Toast
                                .LENGTH_LONG)
                                .show();
                        Log.v("mamaip", longitude);
                        Log.v("mmp", dimension);
                        requestWeb();
                    }
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                    Toast.makeText(getActivity().getApplicationContext(), "定位失败，请打开定位功能", Toast
                            .LENGTH_LONG)
                            .show();
                }
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(mLocationClient!=null){
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
    }
}
